<script setup>
import { useAppStore, useWMTSStore } from '@/stores'
import ExceptionLogger from '@/utils/errorHandler'
import { useBoolean } from '@/hooks/useBoolean'
import L from 'leaflet'
import proj4 from 'proj4'
import { CRS } from '@supermapgis/iclient-leaflet'

const appStore = useAppStore()
const wmtsStore = useWMTSStore()
const selectedValue = ref('')
const wmtsURL = ref('')
const windowWidth = ref(window.innerWidth)
const windowHeight = ref(window.innerHeight)
const adaptHeight = appStore.showTabs ? (appStore.showFooter ? ref(387) : ref(427)) : appStore.showFooter ? ref(427) : ref(472)
const options = ref([])
const loading = ref(false)
const { bool: addLoading, setTrue: startLoading, setFalse: endLoading } = useBoolean(false)
const computedHeight = computed(() => windowHeight.value - adaptHeight.value)

const handleResize = () => {
  windowWidth.value = window.innerWidth
  windowHeight.value = window.innerHeight
}

const handleUpdateValue = async (_, option) => {
  startLoading()
  try {
    wmtsStore.setCurrentTileMatrixSet(option.label)
    await wmtsStore.setLeafletAddCode()
    if (window.LMap_wmts) {
      window.LMap_wmts.remove()
      window.LMap_wmts = null
    }
    eval(wmtsStore.leafletAddCode)
  } catch (error) {
    ExceptionLogger.wmtsHandleException(error)
  } finally {
    endLoading()
  }
}

const load = async () => {
  if (!ExceptionLogger.isValidURL(wmtsURL.value)) return ExceptionLogger.logException('请输入正确的 URL 地址')
  loading.value = true
  startLoading()
  try {
    await wmtsStore.initWMTSInfo(wmtsURL.value)
    await wmtsStore.setLeafletAddCode()
    if (window.LMap_wmts) {
      window.LMap_wmts.remove()
      window.LMap_wmts = null
    }
    eval(wmtsStore.leafletAddCode)
  } catch (error) {
    ExceptionLogger.wmtsHandleException(error)
  } finally {
    loading.value = false
    endLoading()
  }
}

// 初始化地图
function initMap() {
  proj4.defs('EPSG:3857', '+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs +type=crs')
  window.LMap_wmts = L.map(document.getElementById('LMap_wmts'), {
    crs: new L.Proj.CRS('EPSG:3857', {
      origin: L.point(-20037508.342789087, 20037508.342789248),
      resolutions: [156543.0339280409, 78271.51696402059, 39135.75848201029, 19567.879241005117, 9783.939620502559, 4891.969810251267, 2445.9849051256388, 1222.9924525628205, 611.4962262814089, 305.7481131407058, 152.87405657035234, 76.43702828517617, 38.218514142588226]
    })
  })
  new L.supermap.WMTSLayer('https://iserver.supermap.io/iserver/services/map-china400/wmts100', {
    layer: 'China',
    style: 'default',
    tilematrixSet: 'Custom_China',
    format: 'image/png',
    requestEncoding: 'KVP'
  }).addTo(LMap_wmts)
  LMap_wmts.fitBounds(
    L.latLngBounds([
      [-85.05112877980652, -180.00000000000006],
      [85.05112877980648, 180.00000000000003]
    ])
  )
  new CRS('EPSG:3857', {
    origin: [-20037508.342789244, 20037508.342789244]
  })
}

onMounted(async () => {
  window.addEventListener('resize', handleResize)
  initMap()
})

onUnmounted(() => window.removeEventListener('resize', handleResize))

watch(
  () => wmtsStore.wmtsInfo.mapLayer,
  () => {
    if (Array.isArray(wmtsStore.wmtsInfo.mapLayer) && wmtsStore.wmtsInfo.mapLayer.length != 0) {
      options.value = wmtsStore.wmtsInfo.mapLayer.map((item) => {
        return {
          label: item.Title,
          key: item.Identifier,
          children: item.TileMatrixSet.map((matrix) => ({
            label: matrix.TileMatrixSetName,
            key: matrix.TileMatrixSetName
          }))
        }
      })
      selectedValue.value = options.value[0].children[0].label
    }
  }
)
watch(
  () => appStore.showTabs,
  () => (appStore.showTabs ? (adaptHeight.value += 45) : (adaptHeight.value -= 45)),
  { immediate: true }
)
watch(
  () => appStore.showFooter,
  () => (appStore.showFooter ? (adaptHeight.value += 40) : (adaptHeight.value -= 40)),
  { immediate: true }
)
</script>

<template>
  <n-card class="flex-1">
    <n-grid :x-gap="0" :y-gap="8" :cols="2">
      <n-gi>
        <n-flex>
          <n-input-group>
            <n-input v-model:value="wmtsURL" placeholder="请输入WMTS能力文档地址" />
            <n-button type="primary" :loading="loading" @click="load">
              <template #icon>
                <icon-park-outline-loading />
              </template>
              加载
            </n-button>
          </n-input-group>
        </n-flex>
      </n-gi>
      <n-gi>
        <n-flex class="max-w-[240px] ml-auto">
          <n-tree-select :options="options" placeholder="请选择要加载的地图矩阵集合" v-model:value="selectedValue" @update:value="handleUpdateValue" check-strategy="child" />
        </n-flex>
      </n-gi>
    </n-grid>
  </n-card>
  <n-card :style="{ height: `${computedHeight}px` }" class="flex-1 mt-2">
    <div id="LMap_wmts" class="absolute-full"></div>
    <Loading v-if="addLoading" />
  </n-card>
</template>
